using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace LiteDb
{
    public class LiteDbManager : IDisposable
    {
        private readonly LiteDatabase _db;
        public MonitorPortRepository MonitorPortRepo { get; }
        public MonitorDeviceRepository MonitorDeviceRepo { get; }
        public MonitorVariantRepository MonitorVariantRepo { get; }
        public DeviceFixedSettingRepository DeviceFixedSettingRepo { get; }
        public NetworkMqttSettingRepository NetworkMqttSettingRepo { get; }
        public MqttFormatJsonRepository MqttFormatJsonRepo { get; }
        public ConfigSettingRepository ConfigSettingRepo { get; }

        public LiteDbManager(LiteDatabase db)
        {
            _db = db;
            // 初始化数据库
            MonitorPortRepo = new MonitorPortRepository(_db);
            MonitorDeviceRepo = new MonitorDeviceRepository(_db);
            MonitorVariantRepo = new MonitorVariantRepository(_db);
            DeviceFixedSettingRepo = new DeviceFixedSettingRepository(_db);
            NetworkMqttSettingRepo = new NetworkMqttSettingRepository(_db);
            MqttFormatJsonRepo = new MqttFormatJsonRepository(_db);
            ConfigSettingRepo = new ConfigSettingRepository(_db);

            // 初始化数据库
            _db.GetCollection<MonitorPort>(MonitorPort.CollectionName).EnsureIndex(x => x.Id);
            _db.GetCollection<MonitorDevice>(MonitorDevice.CollectionName).EnsureIndex(x => x.Id);
            _db.GetCollection<MonitorVariant>(MonitorVariant.CollectionName).EnsureIndex(x => x.Id);
            _db.GetCollection<DeviceFixedSetting>(DeviceFixedSetting.CollectionName).EnsureIndex(x => x.Id);
            _db.GetCollection<NetworkMqttSetting>(NetworkMqttSetting.CollectionName).EnsureIndex(x => x.Id);
            _db.GetCollection<MqttFormatJson>(MqttFormatJson.CollectionName).EnsureIndex(x => x.Id);
            _db.GetCollection<ConfigSetting>(ConfigSetting.CollectionName).EnsureIndex(x => x.Key);
        }

        public void Dispose()
        {
            _db?.Dispose();
        }

        /// <summary>
        /// 生成文件主方法
        /// </summary>
        public object GenerateFile(object param)
        {
            try
            {
                // 确保download目录存在
                string downloadPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "download");
                if (!Directory.Exists(downloadPath))
                {
                    Directory.CreateDirectory(downloadPath);
                }

                // 清空download文件夹中的所有文件
                ClearDownloadFolder(downloadPath);

                var result = new List<string>();

                // 1. 生成端口配置文件
                var portResult = GeneratePortConfigFile(downloadPath);
                if (portResult.IsSuccess)
                {
                    result.Add("PORTConfig.json 生成成功");
                }

                // 2. 生成设备配置文件
                var deviceResult = GenerateDeviceConfigFile(downloadPath);
                if (deviceResult.IsSuccess)
                {
                    result.Add("DEVConfig.json 生成成功");
                }

                // 3. 生成变量配置文件
                var variantResult = GenerateVariantConfigFiles(downloadPath);
                if (variantResult.IsSuccess)
                {
                    result.Add("变量配置文件生成成功");
                }

                // 4. 生成MQTT配置文件
                var mqttResult = GenerateMqttConfigFile(downloadPath);
                if (mqttResult.IsSuccess)
                {
                    result.Add("MQTTConfig.json 生成成功");
                }

                // 5. 生成网络配置文件
                var networkResult = GenerateNetworkConfigFile(downloadPath);
                if (networkResult.IsSuccess)
                {
                    result.Add("NetworkConfig.json 生成成功");
                }

                // 6. 生成MQTT格式配置文件
                var mqttJsonFormatResult = GenerateMqttJsonFormatConfigFile(downloadPath);
                if (mqttJsonFormatResult.IsSuccess)
                {
                    result.Add("MQTTJsonFormatConfig.json 生成成功");
                }

                // 7. 生成Lua脚本配置文件
                var luaScriptResult = GenerateLuaScriptConfigFile(downloadPath);
                if (luaScriptResult.IsSuccess)
                {
                    result.Add("LuaScriptConfig.json 生成成功");
                }
                
                // 检查运行目录是否存在debug.flag文件，如果有这个文件，则打开downloadPath目录
                string debugFlagPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "debug.flag");
                if (File.Exists(debugFlagPath))
                {
                    System.Diagnostics.Process.Start("explorer.exe", downloadPath);
                }
                return ApiResponse.Success(result, "所有配置文件生成完成");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"生成文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 清空download文件夹中的所有文件
        /// </summary>
        private void ClearDownloadFolder(string downloadPath)
        {
            try
            {
                if (Directory.Exists(downloadPath))
                {
                    // 删除所有文件
                    string[] files = Directory.GetFiles(downloadPath);
                    foreach (string file in files)
                    {
                        try
                        {
                            File.Delete(file);
                        }
                        catch (Exception ex)
                        {
                            // 记录删除失败的文件，但不中断整个流程
                            Console.WriteLine($"删除文件失败: {file}, 错误: {ex.Message}");
                        }
                    }

                    // 删除所有子目录
                    string[] directories = Directory.GetDirectories(downloadPath);
                    foreach (string directory in directories)
                    {
                        try
                        {
                            Directory.Delete(directory, true);
                        }
                        catch (Exception ex)
                        {
                            // 记录删除失败的子目录，但不中断整个流程
                            Console.WriteLine($"删除目录失败: {directory}, 错误: {ex.Message}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"清空download文件夹失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 确保文件目录存在并写入文件
        /// </summary>
        private void WriteFileWithDirectoryCheck(string filePath, string content)
        {
            try
            {
                // 需要判断filePath是否为空
                if (string.IsNullOrEmpty(filePath))
                {
                    throw new Exception("文件路径为空");
                }
                // 确保目录存在
                string? directory = Path.GetDirectoryName(filePath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                // 如果文件存在，则删除
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                // 重新创建文件
                if(!File.Exists(filePath))
                {
                    File.Create(filePath).Close();
                }

                // 写入文件
                File.WriteAllText(filePath, content);
            }
            catch (Exception ex)
            {
                throw new Exception($"写入文件失败: {filePath}, 错误: {ex.Message}");
            }
        }

        /// <summary>
        /// 生成端口配置文件
        /// </summary>
        private ApiResponse GeneratePortConfigFile(string downloadPath)
        {
            try
            {
                // 使用 null! 告诉编译器这个 null 是安全的
                var portResult = MonitorPortRepo.FindAll(null!);
                if (portResult is ApiResponse apiResponse && apiResponse.IsSuccess)
                {
                    string filePath = Path.Combine(downloadPath, "PORTConfig.json");
                    
                    // 解析返回的JSON数据，提取extra字段内容
                    string jsonData = apiResponse.data?.ToString() ?? "[]";
                    var ports = JsonConvert.DeserializeObject<List<dynamic>>(jsonData);
                    
                    var extractedData = new List<object>();
                    
                    if (ports != null)
                    {
                        foreach (var port in ports)
                        {
                            var portObj = port as JObject;
                            if (portObj != null)
                            {
                                // 获取extra字段的内容
                                string extraContent = portObj["extra"]?.ToString() ?? "{}";
                                
                                // 如果extra不为空，解析并添加到结果中
                                if (!string.IsNullOrEmpty(extraContent) && extraContent != "{}")
                                {
                                    try
                                    {
                                        var extraObj = JsonConvert.DeserializeObject(extraContent);
                                        if (extraObj == null)
                                        {
                                            throw new Exception("extra内容解析失败");
                                        }
                                        extractedData.Add(extraObj);
                                    }
                                    catch
                                    {
                                        // 如果extra解析失败，使用原始的port对象（去除extra字段）
                                        var portWithoutExtra = new
                                        {
                                            id = portObj["id"],
                                            name = portObj["name"],
                                            groupDeviceId = portObj["groupDeviceId"]
                                        };
                                        extractedData.Add(portWithoutExtra);
                                    }
                                }
                                else
                                {
                                    // 如果没有extra数据，使用基本字段
                                    var portBasic = new
                                    {
                                        id = portObj["id"],
                                        name = portObj["name"],
                                        groupDeviceId = portObj["groupDeviceId"]
                                    };
                                    extractedData.Add(portBasic);
                                }
                            }
                        }
                    }
                    
                    string content = JsonConvert.SerializeObject(extractedData, Formatting.Indented);
                    WriteFileWithDirectoryCheck(filePath, content);
                    DidaManager.Models.JsonConvert.PortConfigToDownloadFile.ParseDbJsonAndSave(filePath);
                    return ApiResponse.Success(filePath, "端口配置文件生成成功");
                }
                else
                {
                    return ApiResponse.Fail("获取端口数据失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"生成端口配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 生成设备配置文件
        /// </summary>
        private ApiResponse GenerateDeviceConfigFile(string downloadPath)
        {
            try
            {
                // 获取所有设备数据
                var deviceResult = MonitorDeviceRepo.FindAll(null!);
                if (deviceResult is ApiResponse apiResponse && apiResponse.IsSuccess)
                {
                    string filePath = Path.Combine(downloadPath, "DEVConfig.json");

                    // 解析返回的JSON数据，提取extra字段内容
                    string jsonData = apiResponse.data?.ToString() ?? "[]";
                    var devs = JsonConvert.DeserializeObject<List<dynamic>>(jsonData);

                    var extractedData = new List<object>();

                    if (devs != null)
                    {
                        foreach (var dev in devs)
                        {
                            var devObj = dev as JObject;
                            if (devObj != null)
                            {
                                // 获取extra字段的内容
                                string extraContent = devObj["extra"]?.ToString() ?? "{}";

                                // 如果extra不为空，解析并添加到结果中
                                if (!string.IsNullOrEmpty(extraContent) && extraContent != "{}")
                                {
                                    try
                                    {
                                        var extraObj = JsonConvert.DeserializeObject<JObject>(extraContent) ?? new JObject();
                                        if (extraObj == null)
                                        {
                                            throw new Exception("extra内容解析失败");
                                        }
                                        // 需要获取monitor_port_id的值
                                        var monitorPortId = extraObj["monitor_port_id"]?.Value<int>() ?? 0;
                                        var monitorPort = MonitorPortRepo.FindById(monitorPortId);
                                        if (monitorPort is ApiResponse monitorPortApiResponse && monitorPortApiResponse.IsSuccess)
                                        {
                                            MonitorPort? monitorPort1 = monitorPortApiResponse.data as MonitorPort;
                                            if (monitorPort1 == null)
                                            {
                                                throw new Exception("extra内容解析失败");
                                            }
                                            extraObj["port_name"] = monitorPort1.Name;
                                        }
                                        extractedData.Add(extraObj);
                                    }
                                    catch
                                    {
                                        // 如果extra解析失败，使用原始的port对象（去除extra字段）
                                        var portWithoutExtra = new
                                        {
                                            id = devObj["id"],
                                            name = devObj["name"],
                                            groupDeviceId = devObj["groupDeviceId"]
                                        };
                                        extractedData.Add(portWithoutExtra);
                                    }
                                }
                                else
                                {
                                    // 如果没有extra数据，使用基本字段
                                    var portBasic = new
                                    {
                                        id = devObj["id"],
                                        name = devObj["name"],
                                        groupDeviceId = devObj["groupDeviceId"]
                                    };
                                    extractedData.Add(portBasic);
                                }
                            }
                        }
                    }

                    string content = JsonConvert.SerializeObject(extractedData, Formatting.Indented);
                    WriteFileWithDirectoryCheck(filePath, content);
                    DidaManager.Models.JsonConvert.DeviceConfigToDownloadFile.ParseDbJsonAndSave(filePath);
                    return ApiResponse.Success(filePath, "设备配置文件生成成功");
                }
                else
                {
                    return ApiResponse.Fail("获取设备数据失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"生成设备配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 生成变量配置文件（按端口-设备-变量数量规则分文件）
        /// </summary>
        private ApiResponse GenerateVariantConfigFiles(string downloadPath)
        {
            try
            {
                // 获取所有端口数据
                var portResult = MonitorPortRepo.FindAll(null!);
                if (!(portResult is ApiResponse portApiResponse) || !portApiResponse.IsSuccess)
                {
                    return ApiResponse.Fail("获取端口数据失败");
                }

                string portJsonData = portApiResponse.data?.ToString() ?? "[]";
                var ports = JsonConvert.DeserializeObject<List<dynamic>>(portJsonData);

                if (ports == null || ports.Count == 0)
                {
                    // 如果没有端口，创建一个空文件
                    string filePath = Path.Combine(downloadPath, "VARConfig1.json");
                    var emptyConfig = new { VARConfigs = new List<object>() };
                    WriteFileWithDirectoryCheck(filePath, JsonConvert.SerializeObject(emptyConfig, Formatting.Indented));
                    DidaManager.Models.JsonConvert.VarConfigToConfigFile.ParseDbJsonAndSave(filePath);
                    return ApiResponse.Success("VARConfig1.json", "变量配置文件生成成功（空文件）");
                }

                const int maxVariantsPerFile = 30;
                int fileIndex = 1;
                var generatedFiles = new List<string>();
                var currentFileVariants = new List<object>();
                int currentFileVariantCount = 0;

                // 遍历所有端口
                foreach (var port in ports)
                {
                    var portObj = port as JObject;
                    if (portObj == null) continue;

                    int portId = portObj["id"]?.Value<int>() ?? 0;
                    string portName = portObj["name"]?.ToString() ?? "";

                    // 获取该端口下的所有设备
                    var deviceResult = GetMonitorDevicesByGroupId(portId);
                    if (!(deviceResult is ApiResponse deviceApiResponse) || !deviceApiResponse.IsSuccess)
                    {
                        continue;
                    }

                    string deviceJsonData = deviceApiResponse.data?.ToString() ?? "[]";
                    var devices = JsonConvert.DeserializeObject<List<dynamic>>(deviceJsonData);

                    if (devices == null) continue;

                    // 遍历该端口下的所有设备
                    foreach (var device in devices)
                    {
                        var deviceObj = device as JObject;
                        if (deviceObj == null) continue;

                        int deviceId = deviceObj["Id"]?.Value<int>() ?? 0;
                        string devName = deviceObj["Name"]?.ToString() ?? "";

                        // 获取该设备下的所有变量
                        var variantResult = GetMonitorVariantsByGroupId(deviceId);
                        if (!(variantResult is ApiResponse variantApiResponse) || !variantApiResponse.IsSuccess)
                        {
                            continue;
                        }

                        string variantJsonData = variantApiResponse.data?.ToString() ?? "[]";
                        var variants = JsonConvert.DeserializeObject<List<dynamic>>(variantJsonData);

                        if (variants == null || variants.Count == 0) continue;

                        // 处理该设备的变量
                        var deviceVariants = new List<JObject>();
                        foreach (var variant in variants)
                        {
                            var variantObj = variant as JObject;

                            if (variantObj == null) continue;

                            // 需要获取variantObj的extra字段
                            string extraContent = variantObj["Extra"]?.ToString() ?? "{}";
                            if (!string.IsNullOrEmpty(extraContent) && extraContent != "{}")
                            {
                                var extraObj = JsonConvert.DeserializeObject<JObject>(extraContent) ?? new JObject();
                                if (extraObj != null)
                                {
                                    deviceVariants.Add(extraObj);
                                }
                            }
                        }

                        // 规则2：如果设备变量超过30个，按30个切割
                        if (deviceVariants.Count > maxVariantsPerFile)
                        {
                            // 先保存当前文件（如果有内容）
                            if (currentFileVariantCount > 0)
                            {
                                SaveCurrentFile(downloadPath, ref fileIndex, ref generatedFiles, ref currentFileVariants, ref currentFileVariantCount);
                            }

                            // 按30个切割设备变量
                            for (int i = 0; i < deviceVariants.Count; i += maxVariantsPerFile)
                            {
                                var batch = deviceVariants.Skip(i).Take(maxVariantsPerFile).ToList();
                                
                                var config = new
                                {
                                    VarList = batch,
                                    PortName = portName,
                                    DevName = devName
                                };

                                currentFileVariants.Add(config);
                                currentFileVariantCount += batch.Count;

                                // 如果当前文件达到30个变量，保存文件
                                if (currentFileVariantCount >= maxVariantsPerFile)
                                {
                                    SaveCurrentFile(downloadPath, ref fileIndex, ref generatedFiles, ref currentFileVariants, ref currentFileVariantCount);
                                }
                            }
                        }
                        else
                        {
                            // 规则1：设备变量少于30个，检查是否可以添加到当前文件
                            if (currentFileVariantCount + deviceVariants.Count <= maxVariantsPerFile)
                            {
                                // 可以添加到当前文件
                                var config = new
                                {
                                    VarList = deviceVariants,
                                    PortName = portName,
                                    DevName = devName
                                };

                                currentFileVariants.Add(config);
                                currentFileVariantCount += deviceVariants.Count;
                            }
                            else
                            {
                                // 当前文件放不下，先保存当前文件，然后开始新文件
                                SaveCurrentFile(downloadPath, ref fileIndex, ref generatedFiles, ref currentFileVariants, ref currentFileVariantCount);

                                // 开始新文件
                                var config = new
                                {
                                    VarList = deviceVariants,
                                    PortName = portName,
                                    DevName = devName
                                };

                                currentFileVariants.Add(config);
                                currentFileVariantCount += deviceVariants.Count;
                            }
                        }
                    }
                }

                // 保存最后一个文件（如果有内容）
                if (currentFileVariantCount > 0)
                {
                    SaveCurrentFile(downloadPath, ref fileIndex, ref generatedFiles, ref currentFileVariants, ref currentFileVariantCount);
                }

                // 如果没有生成任何文件，创建一个空文件
                if (generatedFiles.Count == 0)
                {
                    string filePath = Path.Combine(downloadPath, "VARConfig1.json");
                    var emptyConfig = new { VARConfigs = new List<object>() };
                    WriteFileWithDirectoryCheck(filePath, JsonConvert.SerializeObject(emptyConfig, Formatting.Indented));
                    DidaManager.Models.JsonConvert.VarConfigToConfigFile.ParseDbJsonAndSave(filePath);
                    generatedFiles.Add("VARConfig1.json");
                }

                return ApiResponse.Success(generatedFiles, $"生成了 {generatedFiles.Count} 个变量配置文件");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"生成变量配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 生成可编辑json配置文件
        /// </summary>
        private ApiResponse GenerateMqttJsonFormatConfigFile(string downloadPath)
        {
            try
            {
                // 获取所有设备数据
                var mqttResult = MqttFormatJsonRepo.FindAllMqttFormatListByOrder(null!);
                if (mqttResult is ApiResponse apiResponse && apiResponse.IsSuccess)
                {
                    string filePath = Path.Combine(downloadPath, "MQTTJsonFormatConfig.json");

                    // 解析返回的JSON数据，提取extra字段内容
                    string jsonData = apiResponse.data?.ToString() ?? "[]";
                    var mqttAll = JsonConvert.DeserializeObject<List<dynamic>>(jsonData);

                    var extractedData = new List<object>();

                    if (mqttAll == null)
                    {
                        return ApiResponse.Success(filePath, "MQTT格式配置文件生成成功,但是内容全部为空");
                    }

                    const string strPreMqtt = "Mqtt_";
                    foreach (var mqtt in mqttAll)
                    {
                        var mqttObj = mqtt as JObject;
                        if (mqttObj == null)
                        {
                            continue;
                        }
                        // 获取extra字段的内容
                        string extraContent = mqttObj["Extra"]?.ToString() ?? "{}";
                        string id = mqttObj["Id"]?.ToString()?? "";

                        // 如果extra不为空，解析并添加到结果中
                        if (!string.IsNullOrEmpty(extraContent) && extraContent != "{}")
                        {
                            try
                            {
                                var extraObj = JsonConvert.DeserializeObject<JObject>(extraContent) ?? new JObject();
                                if (extraObj == null)
                                {
                                    throw new Exception("extra内容解析失败");
                                }
                                // 需要获取monitor_port_id的值
                                var extraData = extraObj["extra"]?.Value<object>() ?? new object();
                                if (extraData != null)
                                {
                                    // 获取 publishSchemaFile
                                    var publishSchemaFile = ((JObject)extraData)["publishSchemaFile"];
                                    if (publishSchemaFile != null)
                                    {
                                        var publishData = publishSchemaFile["data"]?.ToString();
                                        if (publishData != null)
                                        {
                                            // id_pub.json
                                            string publishFileName = strPreMqtt + id + "_Pub.json";
                                            string publishFilePath = Path.Combine(downloadPath, publishFileName);
                                            WriteFileWithDirectoryCheck(publishFilePath, publishData);
                                        }
                                    }

                                    // 获取 subscribeSchemaFile
                                    var subscribeSchemaFile = ((JObject)extraData)["subscribeSchemaFile"];
                                    if (subscribeSchemaFile != null)
                                    {
                                        var subscribeData = subscribeSchemaFile["data"]?.ToString();
                                        if (subscribeData != null)
                                        {
                                            // id_sub.json
                                            string subscribeFileName = strPreMqtt + id + "_Sub.json";
                                            string subscribeFilePath = Path.Combine(downloadPath, subscribeFileName);
                                            WriteFileWithDirectoryCheck(subscribeFilePath, subscribeData);
                                        }
                                    }
                                }
                            }
                            catch
                            {
                                // 如果extra解析失败，使用原始的port对象（去除extra字段）
                                var mqttWithoutExtra = new
                                {
                                    id = mqttObj["id"],
                                    name = mqttObj["name"],
                                    groupDeviceId = mqttObj["groupDeviceId"]
                                };
                                extractedData.Add(mqttWithoutExtra);
                            }
                        }
                        else
                        {
                            // 如果没有extra数据，使用基本字段
                            var mqttBasic = new
                            {
                                id = mqttObj["id"],
                                name = mqttObj["name"],
                                groupDeviceId = mqttObj["groupDeviceId"]
                            };
                            extractedData.Add(mqttBasic);
                        }
                    }                    
                    return ApiResponse.Success(filePath, "MQTT格式配置文件生成成功");
                }
                else
                {
                    return ApiResponse.Fail("获取MQTT格式配置数据失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"生成MQTT格式配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 生成Lua脚本配置文件
        /// </summary>
        private ApiResponse GenerateLuaScriptConfigFile(string downloadPath)
        {
            try
            {
                // 获取所有Lua脚本配置数据
                var luaScriptResult = ConfigSettingRepo.GetConfig(ConfigSettingEnum.Lua_Script);
                if (luaScriptResult is ApiResponse apiResponse && apiResponse.IsSuccess)
                {
                    string filePath = Path.Combine(downloadPath, "luaScript.lua");
                    string content = apiResponse.data?.ToString() ?? "[]";
                    WriteFileWithDirectoryCheck(filePath, content);
                    return ApiResponse.Success(filePath, "Lua脚本配置文件生成成功");
                }
                else
                {
                    return ApiResponse.Fail("获取Lua脚本配置数据失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"生成Lua脚本配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 保存当前文件
        /// </summary>
        private void SaveCurrentFile(string downloadPath, ref int fileIndex, ref List<string> generatedFiles, 
            ref List<object> currentFileVariants, ref int currentFileVariantCount)
        {
            if (currentFileVariants.Count > 0)
            {
                string fileName = $"VARConfig{fileIndex}.json";
                string filePath = Path.Combine(downloadPath, fileName);
                
                var batchConfig = new { VARConfigs = currentFileVariants };
                string batchJson = JsonConvert.SerializeObject(batchConfig, Formatting.Indented);
                WriteFileWithDirectoryCheck(filePath, batchJson);
                DidaManager.Models.JsonConvert.VarConfigToConfigFile.ParseDbJsonAndSave(filePath);
                generatedFiles.Add(fileName);
                fileIndex++;

                // 重置当前文件状态
                currentFileVariants = new List<object>();
                currentFileVariantCount = 0;
            }
        }

        /// <summary>
        /// 生成MQTT配置文件
        /// </summary>
        private ApiResponse GenerateMqttConfigFile(string downloadPath)
        {
            try
            {
                // 获取所有MQTT配置数据
                var mqttResult = NetworkMqttSettingRepo.FindAll(null);
                if (mqttResult is ApiResponse apiResponse && apiResponse.IsSuccess)
                {
                    string filePath = Path.Combine(downloadPath, "MQTTConfig.json");
                    string content = apiResponse.data?.ToString() ?? "[]";
                    WriteFileWithDirectoryCheck(filePath, content);
                    var dict = MqttFormatJsonRepo.FindAllMqttFormatListByOrderDict();
                    DidaManager.Models.JsonConvert.MqttConvertToDownloadFile.ParseDbJsonAndSave(filePath,dict);
                    return ApiResponse.Success(filePath, "MQTT配置文件生成成功");
                }
                else
                {
                    return ApiResponse.Fail("获取MQTT配置数据失败");
                }
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"生成MQTT配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 生成网络配置文件
        /// </summary>
        private ApiResponse GenerateNetworkConfigFile(string downloadPath)
        {
            try
            {
                object param = new object();
                // 获取本地网络配置
                var localResult = DeviceFixedSettingRepo.GetLocalNetworkSettings(param);
                if (localResult is ApiResponse localApiResponse && localApiResponse.IsSuccess)
                {
                    string filePath = Path.Combine(downloadPath, "NetworkConfig.json");
                    string jsonContent = localApiResponse.data?.ToString() ?? "[]";
                    WriteFileWithDirectoryCheck(filePath, jsonContent);
                    DidaManager.Models.JsonConvert.NetworkToDownloadFile.ParseDbJsonAndSave(filePath);
                }

                // 获取HJ212网络配置
                var hj212Result = DeviceFixedSettingRepo.GetHj212NetworkSettings(param);
                if (hj212Result is ApiResponse hj212ApiResponse && hj212ApiResponse.IsSuccess)
                {
                    string filePath = Path.Combine(downloadPath, "NetworkHj212.json");
                    string jsonContent = hj212ApiResponse.data?.ToString() ?? "[]";
                    WriteFileWithDirectoryCheck(filePath, jsonContent);
                    DidaManager.Models.JsonConvert.Hj212ServerToDownloadFile.ParseDbJsonAndSave(filePath);
                }
                return ApiResponse.Success(downloadPath, "网络配置文件生成成功");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"生成网络配置文件失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 通过串口生成文件
        /// </summary>
        public object GenerateFileViaSerial(object param)
        {
            return GenerateFile(param);
        }

        /// <summary>
        /// 通过网络生成文件
        /// </summary>
        public object GenerateFileViaNetwork(object param)
        {
            return GenerateFile(param);
        }

        // MonitorPort 操作
        public object AddMonitorPort(object param) => MonitorPortRepo.Insert(param);
        public object GetMonitorPort(object param) => MonitorPortRepo.FindById(param);
        public object GetAllMonitorPorts(object param) => MonitorPortRepo.FindAll(param);
        public object GetMonitorPortsByGroupId(object param) => MonitorPortRepo.GetByGroupId(param);
        public object UpdateMonitorPort(object param) => MonitorPortRepo.Update(param);
        public object DeleteMonitorPort(object param) => MonitorPortRepo.Delete(param);
        public object GetBridgePortOptions(object param) => MonitorPortRepo.GetBridgePortOptions(param);

        // MonitorDevice 操作
        public object AddMonitorDevice(object param) => MonitorDeviceRepo.Insert(param);
        public object GetMonitorDevice(object param) => MonitorDeviceRepo.FindById(param);
        public object GetAllMonitorDevices(object param) => MonitorDeviceRepo.FindAll(param);
        public object GetMonitorDevicesByGroupId(object param) => MonitorDeviceRepo.GetByGroupId(param);
        public object UpdateMonitorDevice(object param) => MonitorDeviceRepo.Update(param);
        public object DeleteMonitorDevice(object param) => MonitorDeviceRepo.Delete(param);

        // MonitorVariant 操作
        public object AddMonitorVariant(object param) => MonitorVariantRepo.Insert(param);
        public object AddMonitorVariantBatch(object param) => MonitorVariantRepo.InsertBatch(param);
        public object GetMonitorVariant(object param) => MonitorVariantRepo.FindById(param);
        public object GetAllMonitorVariants(object param) => MonitorVariantRepo.FindAll(param);
        public object GetMonitorVariantsByGroupId(object param) => MonitorVariantRepo.GetByGroupId(param);
        public object UpdateMonitorVariant(object param) => MonitorVariantRepo.Update(param);
        public object DeleteMonitorVariant(object param) => MonitorVariantRepo.Delete(param);

        // 设备固定配置操作 (NetworkLocal, NetworkOray, NetworkHj212)
        public object SaveLocalNetworkSettings(object param) => DeviceFixedSettingRepo.SaveLocalNetworkSettings(param);
        public object GetLocalNetworkSettings(object param) => DeviceFixedSettingRepo.GetLocalNetworkSettings(param);
        public object SaveHj212NetworkSettings(object param) => DeviceFixedSettingRepo.SaveHj212NetworkSettings(param);
        public object GetHj212NetworkSettings(object param) => DeviceFixedSettingRepo.GetHj212NetworkSettings(param);
        public object SaveOrayNetworkSettings(object param) => DeviceFixedSettingRepo.SaveOrayNetworkSettings(param);
        public object GetOrayNetworkSettings(object param) => DeviceFixedSettingRepo.GetOrayNetworkSettings(param);

        // MQTT网络配置操作 (支持完整的增删改查)
        public object AddNetworkMqttSetting(object param) => NetworkMqttSettingRepo.Insert(param);
        public object GetNetworkMqttSetting(object param) => NetworkMqttSettingRepo.FindById(param);
        public object GetAllNetworkMqttSettings(object param) => NetworkMqttSettingRepo.FindAll(param);
        public object UpdateNetworkMqttSetting(object param) => NetworkMqttSettingRepo.Update(param);
        public object DeleteNetworkMqttSetting(object param) => NetworkMqttSettingRepo.Delete(param);
        public object DeleteAllNetworkMqttSettings(object param) => NetworkMqttSettingRepo.DeleteByGroupDeviceId(Convert.ToInt32(param));

        // MqttFormatJson 操作
        public object AddMqttFormatJson(object param) => MqttFormatJsonRepo.Insert(param);
        public object GetMqttFormatJson(object param) => MqttFormatJsonRepo.FindById(param);
        public object GetAllMqttFormatJsons(object param) => MqttFormatJsonRepo.FindAll(param);
        public object UpdateMqttFormatJson(object param) => MqttFormatJsonRepo.Update(param);
        public object DeleteMqttFormatJson(object param) => MqttFormatJsonRepo.Delete(param);
        public object GetMqttFormatJsonDeviceTree(object param) => MonitorPortRepo.GetAllMonitorPortAndDeviceNames(param);
        public object GetMqttFormatJsonDevicesVarJson(object param) => MonitorVariantRepo.FindAllMqttFormatDevicesJson(param);
        public object GetMqttCustomTopicList(object param) => MqttFormatJsonRepo.FindAllMqttFormatList(param);

        // ConfigSetting 操作
        public object SaveConfig(object param) => ConfigSettingRepo.SaveConfig(param);
        public object GetConfig(object param) => ConfigSettingRepo.GetConfig(param);
        public object GetAllConfigs(object param) => ConfigSettingRepo.GetAllConfigs(param);
        public object DeleteConfig(object param) => ConfigSettingRepo.DeleteConfig(param);

        // 获取当前硬件使用资源数量
        public object GetHardwareCount(object param)
        {
            try
            {
                // 获取端口
                var hardwareCount = MonitorPortRepo.GetHardwareCount();
                // 获取设备
                var deviceCount = MonitorDeviceRepo.GetHardwareCount();
                // 获取变量
                var variantCount = MonitorVariantRepo.GetHardwareCount();
                // 获取MQTT
                var mqttCount = NetworkMqttSettingRepo.GetHardwareCount();
                var dict = new Dictionary<string, int>
                {
                    { "port", hardwareCount },
                    { "device", deviceCount },
                    { "variable", variantCount },
                    { "mqtt", mqttCount }
                };
                // 转为json字符串
                string json = JsonConvert.SerializeObject(dict);
                return ApiResponse.Success(json);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail($"获取当前硬件使用资源数量失败: {ex.Message}");
            }
        }
    }

    public class CefSharpServer
    {
        private readonly LiteDbManager _dbManager;

        public CefSharpServer(LiteDatabase db)
        {
            _dbManager = new LiteDbManager(db);
        }

        public Task<object?> CallMethod(string methodName, object param)
        {
            var type = _dbManager.GetType();
            var method = type.GetMethod(methodName, new[] { typeof(object) });
            if (method == null)
            {
                return Task.FromResult<object?>(ApiResponse.NotFound());
            }

            var result = method.Invoke(_dbManager, new[] { param });
            // 如果本来就是 Task<object?>，直接返回  
            if (result is Task<object?> taskObj)
                return taskObj;
            // 否则包一层 Task  
            return Task.FromResult<object?>(result);
        }
    }
} 